<template>
  <div class="app-container">
    <el-row class="order-state-row">
      <el-col>
        <div style="margin:0 0 20px 0;">
          <span style="margin-right:14px">售后状态</span>
          <el-radio-group
            v-model="queryParams.status"
            size="mini"
            @input="network().getList()"
          >
            <el-radio-button :label="undefined">全部</el-radio-button>
            <el-radio-button label="0">待审核</el-radio-button>
            <el-radio-button label="4">退款成功</el-radio-button>
            <el-radio-button label="7">退款关闭</el-radio-button>
            <el-radio-button label="5">已取消</el-radio-button>
          </el-radio-group>
        </div>
      </el-col>
    </el-row>
    <dk-query
      ref="nxIB"
      :searchForm="queryParams"
      :inputList="inputList"
      :queryTable="click().handleQuery"
      labelWidth="110"
    >
    </dk-query>
    <dk-table
      ref="table"
      :column="column"
      :pagination="paginationObjs"
      :tableData="tableData"
      :height="tableHeight"
    >
    </dk-table>
    <!-- 审核弹窗 -->
    <el-dialog
      title="审核"
      :visible.sync="audit.auditDialog"
      width="30%"
      class="dialog-container"
      :before-close="closeDialog"
    >
      <el-form
        ref="dialogData"
        :rules="audit.dialogRules"
        label-suffix=":"
        :model="audit.dialogData"
      >
        <el-form-item
          prop="auditStatus"
          label="审核意见"
          label-width="90px"
        >
          <el-select
            v-model="audit.dialogData.auditStatus"
            placeholder="请选择"
            size="mini"
          >
            <el-option
              label="通过"
              value="1"
            ></el-option>
            <el-option
              label="驳回"
              value="2"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="audit.dialogData.auditStatus == '1'"
          label="退款金额"
          prop="refundRmb"
          label-width="90px"
        >
          <el-input
            placeholder="请输入金额"
            v-model="audit.dialogData.refundRmb"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="audit.dialogData.auditStatus == '1'"
          prop="remarkVal"
          label="备注"
          label-width="90px"
        >
          <el-input
            placeholder="请输入，最多100字"
            v-model="audit.remarkVal"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          prop="auditReason"
          label="驳回理由"
          label-width="90px"
          v-if="audit.dialogData.auditStatus == '2'"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入驳回理由,最多输入100字"
            v-model="audit.dialogData.auditReason"
          >
          </el-input>
        </el-form-item>

      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="click().handleClose('dialogData')">取 消</el-button>
        <el-button
          type="primary"
          @click="click().handleStatus('dialogData')"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
// 接口api：first step
import {
  getOrderList,
  examineOrder,
  comfirmOrder,
  exportOrder,
} from "@/api/merchant-order-manage/aftermarket-orders.js";
import { getStatusActions } from "@/utils/status.js";
export default {
  data() {
    var validateRmb = (rule, value, callback) => {
      if (+value > +this.payRmb) {
        callback(new Error("退款金额不能大于实付款金额"));
      }
      if (!value) {
        callback(new Error());
      } else {
        callback();
      }
    };
    return {
      loading: true,
      // 类型，1-商家配送，2-门店自提,3-会员服务
      type: 3,
      // 表格退款金额
      payRmb: "",
      // 门店自提 - 规程toolbar：two step
      inputList: [
        {
          type: "input",
          placeholder: "请输入",
          label: "售后编号",
          name: "returnNo",
        },
        {
          type: "input",
          placeholder: "请输入",
          label: "订单编号",
          name: "orderNo",
        },
        {
          type: "daterange",
          placeholder: "选择日期",
          label: "创建时间",
          name: "dateRange",
          fun: (row) => {
            this.queryParams.dateRange[0] = `${row[0]} 00:00:00`;
            this.queryParams.dateRange[1] = `${row[1]} 23:59:59`;
          },
        },
        {
          type: "input",
          placeholder: "请输入",
          label: "商品名称",
          name: "commodityName",
        },
        {
          type: "input",
          placeholder: "请输入",
          label: "用户昵称",
          name: "userName",
        },
        {
          type: "input",
          placeholder: "请输入",
          label: "手机号",
          name: "telephone",
        },
        {
          type: "common-button",
          isShowExport: true,
          searchFun: (searchForm) => {
            this.queryParams = searchForm;
            this.click().handleQuery();
          },
          resetFun: () => {
            this.click().resetQuery();
          },
          exportFun: () => {
            this.click().handleExport();
          },
        },
      ],
      // 门店自提 - 规程表头：shree step
      column: [
        {
          value: "returnNo",
          name: "售后编号",
        },
        {
          value: "orderNo",
          name: "订单编号",
        },
        {
          value: "goodsName",
          name: "商品名称",
        },
        {
          value: "userNickName",
          name: "用户昵称",
        },
        {
          value: "userPhone",
          name: "手机号码",
        },
        {
          value: "applyRmb",
          name: "退款金额",
        },
        // {
        //   value: "returnType",
        //   name: "售后类型",
        //   stateList: [
        //     { name: "仅退款", value: 0 },
        //     { name: "退货", value: 1 },
        //     { name: "退货退款", value: 2 },
        //   ],
        // },
        {
          value: "status",
          name: "售后状态",
          stateList: [
            { name: "待审核", value: 0 },
            { name: "待寄件", value: 1 },
            { name: "待收件", value: 2 },
            { name: "退款成功", value: 3 },
            /* 会员服务列表售后状态不对,状态4另外取退款成功 */
            // { name: "已取消", value: 4 },
            { name: "退款成功", value: 4 },
            { name: "退款失败", value: 5 },
            { name: "退款关闭", value: 6 },
          ],
        },
        {
          value: "createTime",
          name: "创建时间",
        },
        {
          width: 120,
          value: "id",
          name: "操作",
          fixed: "right",
          type: "button",
          buttonList: [
            {
              type: "no-tooltip",
              name: "审核",
              fun: (row) => {
                this.click().handleAudit(row);
              },
              showFun: (row) => {
                return row.status == 0;
              },
              color: "text",
            },
            {
              type: "no-tooltip",
              name: "确认收件",
              fun: (row) => {
                this.click().handleComfirm(row);
              },
              showFun: (row) => {
                return getStatusActions(row.status).PickUp;
              },
              color: "text",
            },
            {
              type: "no-tooltip",
              name: "详情",
              fun: (row) => {
                this.click().handleDetail(row);
              },
              color: "text",
              hasPermiss: () => `${this.urlObject.permissPrefix}detail`,
            },
          ],
        },
      ],

      // 分页器
      paginationObjs: {
        paginationChange: function () {
          this.network().getList(false);
        }.bind(this),
        page: 1,
        limit: 10,
        total: 0,
        loading: false,
      },
      // 查询参数
      queryParams: { status: undefined },

      // 表格数据
      tableData: [],
      // 审核弹窗对象
      audit: {
        remarkVal: "",

        // 审核弹出框
        auditDialog: false,
        // 审核弹出框弹出框内容
        dialogData: {
          auditReason: "",
          refundRmb: "",
          auditStatus: "",
          id: "",
        },
        // 对话框校验对象
        dialogRules: {
          auditStatus: [
            { required: true, message: "请选择审核意见", trigger: "change" },
          ],
          refundRmb: [
            { required: true, message: "请输入退款金额", trigger: "change" },
            {
              validator: validateRmb,
              required: true,
              message: "退款金额不能大于实付款金额",
              trigger: "change",
            },
          ],
          auditReason: [
            {
              required: true,
              max: 100,
              message: "请输入驳回理由",
              trigger: "blur",
            },
          ],
        },
      },
      // url对象：four step
      urlObject: {
        permissPrefix: "order-manage:aftermarket-orders:",
        routePathPrefix: "/order-manage/AftermarketOrders/",
      },
      // 接口存储对象：five step
      interfaceObj: {
        getApiName: getOrderList,
        examineApiName: examineOrder,
      },
    };
  },

  created() {
    this.network().getList();
    const { uuid } = this.$route.params;
    this.audit.dialogData.id = uuid;
    this.getTableHeight.call(this);
  },
  methods: {
    closeDialog() {
      this.audit.auditDialog = false;
      this.$refs["dialogData"].resetFields();
      this.audit.dialogData.auditStatus = "";
    },

    click() {
      return {
        // 搜索
        handleQuery: async () => {
          this.paginationObjs.page = 1;
          this.network().getList();
        },
        // 重置
        resetQuery: async () => {
          this.queryParams = this.$options.data().queryParams;
          this.paginationObjs.page = 1;
          this.paginationObjs.limit = 10;
          this.network().getList();
        },
        // 详情
        handleDetail: async (row) => {
          this.$router.push({
            path: `${this.urlObject.routePathPrefix}detail/${row.id}`,
            query: {
              returnType: row.returnType,
              status: row.status,
            },
          });
        },
        // 审核
        handleAudit: async (row) => {
          const rmb = this.tableData.find((item) => {
            return item.id == row.id;
          });
          this.payRmb = rmb.applyRmb;
          this.audit.auditDialog = true;
          this.audit.dialogData.id = row.id;
        },
        // 审核 - 取消 - 关闭对话框
        handleClose: async (formName) => {
          this.audit.auditDialog = false;
          this.$refs[formName].resetFields();
          this.audit.dialogData.auditStatus = "";
        },
        // 审核 - 确定 - 关闭对话框
        handleStatus: async (formName) => {
          const throttleStatus = this.throttle(); // 节流
          if (!throttleStatus) return;

          this.$refs[formName].validate((valid) => {
            if (valid) {
              const newObj = JSON.parse(JSON.stringify(this.audit.dialogData));
              newObj.auditStatus = Number(this.audit.dialogData.auditStatus);
              if (newObj.auditStatus == 1) {
                newObj.auditReason = this.audit.remarkVal;
              }
              if (newObj.auditReason == "" && newObj.auditStatus == 2) {
                this.$message({
                  message: "请填写驳回理由",
                  type: "warning",
                });
                return;
              }
              this.network().changeStatus(newObj);
            } else {
              return false;
            }
          });
        },
        // 确认收货
        handleComfirm: async (row) => {
          this.deleteMessageBox({
            message: "是否确认收件？",
            hideTit: true,
          }).then(() => {
            this.network().handleComfirm(row);

          });
        },
      };
    },
    network() {
      return {
        getList: async () => {
          const params = this.deepCopy(this.queryParams);
          delete params.dateRange;
          const obj = {
            ...params,
            pageNum: this.paginationObjs.page,
            pageSize: this.paginationObjs.limit,
            beginTime: this.queryParams.dateRange?.[0],
            afterTime: this.queryParams.dateRange?.[1],
          };
          this.loading = true;
          try {
            const { getApiName } = this.interfaceObj;
            const data = await getApiName({
              ...obj,
              type: this.type,
            });
            this.loading = false;
            this.tableData = data.rows;
            this.paginationObjs.total = data.total;
          } catch (error) {
            this.loading = false;
          }
        },
        // 审核
        changeStatus: async (obj) => {
          const { examineApiName } = this.interfaceObj;
          const data = await examineApiName(obj);
          if (data.code == 0) {
            this.$message.success("提交成功");
            this.audit.auditDialog = false;
            this.network().getList();
            this.$refs["dialogData"].resetFields();
            this.audit.dialogData.auditStatus = "";
            this.audit.remarkVal = "";

            return false;
          }
          return this.$message.error("提交失败");
        },
        handleComfirm: async (id) => {
          const { code } = await comfirmOrder(row.id);

          if (code === 0) {
            this.$modal.msgSuccess("提交成功");
          }
          this.network().getList();
        },
      };
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-message-box__title span {
  position: relative;
  left: 37px !important;
}

::v-deep .cell {
  .el-button {
    &:last-child {
      width: 40px;
      margin-right: 10px;
    }
  }
}
::v-deep .order-state-row {
  padding-left: 0;
}
::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  color: #1890ff;
  background-color: transparent;
}
::v-deep .el-select {
  width: 100%;
  .el-input {
    width: 100%;
  }
}
.app-container span {
  font-size: 14px;
  font-weight: bold;
  color: #606266;
}
</style>